#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

int gval = 100;

std::string ToHex(pthread_t tid)
{
    char id[128];
    snprintf(id, sizeof(id), "%x", tid);
    return id;
}

void *threadRun(void* args)
{
    std::string name = static_cast<const char*>(args);
    while (true)
    {
        std::string id = ToHex(pthread_self());
        std::cout << name << " is running, tid: " << id << ", gval: " << gval << ", &gval" << &gval << std::endl;
        sleep(1);
        gval++;
    }
    
}

int main()
{
    pthread_t tid;
    //给threadRun指向的这个函数传参时，传入的参数类型也可以是一个类指针
    int n = pthread_create(&tid, nullptr, threadRun, (void*)"thread-1");

    while (true)
    {
        std::cout << "main thread, gval: " << gval << ", &gval" << &gval << std::endl;
        sleep(1);
    }
    
    std::cout << "new thread tid: " << ToHex(tid) << std::endl;
    pthread_join(tid, nullptr);
    return 0;
}